import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Teacher } from './entities/teacher.entity';
import { CreateTeacherDto } from './dto/create-teacher.dto';
import { UpdateTeacherDto } from './dto/update-teacher.dto';

@Injectable()
export class TeacherService {
  constructor(
    @InjectRepository(Teacher)
    private readonly teacherRepo: Repository<Teacher>,
  ) {}

  async create(createTeacherDto: CreateTeacherDto): Promise<Teacher> {
    const teacher = this.teacherRepo.create(createTeacherDto);
    return await this.teacherRepo.save(teacher);
  }

  async findAll(page: number = 1, pageSize: number = 10): Promise<{
    list: Teacher[];
    itemCount: number;
    page: number;
    pageSize: number;
    pageCount: number;
  }> {
    const skip = (page - 1) * pageSize;
    const [data, total] = await this.teacherRepo.findAndCount({
      skip,
      take: pageSize,
      order: { tno: 'ASC' }
    });
  
    return {
      list: data,
      itemCount: total,
      page,
      pageSize,
      pageCount: Math.ceil(total / pageSize)
    };
  }

  async findOne(tno: number): Promise<Teacher> {
    const teacher = await this.teacherRepo.findOneBy({ tno });
    if (!teacher) {
      throw new NotFoundException(`Teacher with tno ${tno} not found`);
    }
    return teacher;
  }

  async update(tno: number, updateTeacherDto: UpdateTeacherDto): Promise<Teacher> {
    const teacher = await this.teacherRepo.preload({
      tno,
      ...updateTeacherDto,
    });
    
    if (!teacher) {
      throw new NotFoundException(`Teacher with tno ${tno} not found`);
    }
    
    return this.teacherRepo.save(teacher);
  }

  async remove(tno: number): Promise<void> {
    const result = await this.teacherRepo.delete(tno);
    if (result.affected === 0) {
      throw new NotFoundException(`Teacher with tno ${tno} not found`);
    }
  }
}
